//
//  GlobalAddressManagerViewController.m
//  customer
//
//  Created by Holothurian on 2018/11/3.
//  Copyright © 2018年 yinlong. All rights reserved.
//

#import "GlobalAddressManagerViewController.h"
#import "SelectAddressTableViewCell.h"
#import "AddNewAddressViewController.h"


static NSString *AddressCellId = @"AddressCellId";
static NSString *AddressFooterId = @"AddressFooterId";
@interface GlobalAddressManagerViewController ()<UITableViewDelegate,UITableViewDataSource,SelectAddressTableDelegate,UIAlertViewDelegate>{
    NSInteger _selectIndex;
}

@property (nonatomic,strong)UIScrollView *scrollView;

@end

@implementation GlobalAddressManagerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"选择地址";
    [self layoutTableView];
    [self layoutRightAddBar];
}

- (void)layoutRightAddBar{
    UIView * addBgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];
    UIImageView * addImageView = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 20, 20)];
    addImageView.image = [UIImage imageNamed:@"addressManagerAdd"];
    addImageView.userInteractionEnabled = YES;
    [addBgView addSubview:addImageView];
    UITapGestureRecognizer * backTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(addTapClick)];
    [addBgView addGestureRecognizer:backTap];
    UIBarButtonItem * rightBtnItem = [[UIBarButtonItem alloc]initWithCustomView:addBgView];
    self.navigationItem.rightBarButtonItem = rightBtnItem;
}

- (void)addTapClick{
    AddNewAddressViewController *newAddress = [[AddNewAddressViewController alloc]init];
    TAB_PUSH(self, newAddress, YES);
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.tableView.mj_header beginRefreshing];
}

/**
 地址---用户所有地址列表
 */
- (void)loadDataList{
    [self showLoading];
    NSDictionary *dict = @{@"member_id":K_UserDefault_Read(CustomerUserID)?:@"",@"member_token":K_UserDefault_Read(CustomerUserToken)?:@"",@"page":[NSNumber numberWithInteger:self.page]};
    if (self.page == 1) { [self.dataList removeAllObjects];  }
    AutoWeakSelf
    [[QYNetManager sharedManager]POST:kGetMemberAddress parameters:dict andApiTyp:CustomerApiTypMain SuccessBlock:^(id responseObject) {
        [weakSelf hideLoading];
        [weakSelf endReresh];
        if ([responseObject[@"status"] isEqualToString:@"error"]) {
            [weakSelf showErrorTipWithTitle:responseObject[@"error"]];
        }else{
            if ([responseObject[@"total"]integerValue] == [self.dataList count] || [responseObject[@"total"] integerValue]<10) {
                [weakSelf.tableView.mj_footer removeFromSuperview];
            }
            NSArray *dataSource = responseObject[@"data"];
            [weakSelf.dataList addObjectsFromArray:[NSArray yy_modelArrayWithClass:[AddressModel class] json:dataSource]];
            if (kArrayIsEmpty(self.dataList)) {
                weakSelf.tableView.emptyTitle = @"暂无数据";
                weakSelf.tableView.emptyImg = @"";
                weakSelf.tableView.showEmpty = YES;
                
            }else{
                weakSelf.tableView.showEmpty = NO;
            }
            [weakSelf.tableView reloadData];
        }
    } Failure:^(NSError *error) {
        [weakSelf hideLoading];
        [weakSelf endReresh];
        weakSelf.tableView.showEmpty = YES;
        [weakSelf showErrorTipWithTitle:CustomerPoolNetStr];
    }];
}

- (void)layoutTableView{
    [self.view addSubview:self.scrollView];
    self.tableView.frame = CGRectMake(0, 0, F_DEVICE_W, F_DEVICE_H - NAVIGATION_BAR_HEIGHT - bottomPadding(100));
    self.refreshEnabled = YES;
    [self.scrollView addSubview:self.tableView];
    [self.tableView registerClass:[SelectAddressTableViewCell class] forCellReuseIdentifier:AddressCellId];
    [self.tableView registerClass:[SelectAddressFooterView class] forHeaderFooterViewReuseIdentifier:AddressFooterId];
    
    UIButton *addButton = [UIButton buttonWithType:UIButtonTypeCustom];
    addButton.frame = CGRectMake(30, F_DEVICE_H - NAVIGATION_BAR_HEIGHT - bottomPadding(20), F_DEVICE_W - 60, 50);
    addButton.layer.cornerRadius = 6;
    addButton.layer.masksToBounds = YES;
    [addButton setBackgroundColor:[HSPublic colorWithHexString:@"333333"]];
    [addButton setTitle:@"添加地址" forState:UIControlStateNormal];
    [addButton setTitle:@"添加地址" forState:UIControlStateSelected];
    [addButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [addButton setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    [addButton addTarget:self action:@selector(addTapClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:addButton];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return [self.dataList count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    SelectAddressTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:AddressCellId];
    [cell cellForLayout:self.dataList[indexPath.section]];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.isSelf) {
        return;
    }
    AddressModel *address = self.dataList[indexPath.section];
    if (self.addressBlock) {
        self.addressBlock(address);
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 75.f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 5.f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 40.f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *topView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, F_DEVICE_W, 5)];
    topView.backgroundColor = [UIColor appColor];
    return topView;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    SelectAddressFooterView *footer = [self.tableView dequeueReusableHeaderFooterViewWithIdentifier:AddressFooterId];
    footer.indexPath = [NSIndexPath indexPathForRow:0 inSection:section];
    footer.delegate = self;
    AddressModel *address = self.dataList[section];
    if ([address.is_default integerValue]==1) {
        footer.defaultAddressBtn.selected = YES;
    }else{
        footer.defaultAddressBtn.selected = NO;
    }
    return footer;
}
//
#pragma mark - SelectAddressTableDelegate
- (void)selectAddressSetDefaultAddress:(NSIndexPath *)indexPath{
    NSLog(@"将 %ld 设为默认",indexPath.section);
    if (indexPath.section >= [self.dataList count]) {
        return;
    }
    
    AutoWeakSelf
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@"确认要将该地址设为默认?" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [alertController dismissViewControllerAnimated:YES completion:nil];
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        AddressModel *address = self.dataList[indexPath.section];
        NSDictionary *dict = @{@"member_id":K_UserDefault_Read(CustomerUserID)?:@"",@"member_token":K_UserDefault_Read(CustomerUserToken)?:@"",@"address_id":address.address_id};
        __block typeof(weakSelf) strongSelf = weakSelf;
        [[QYNetManager sharedManager]POST:kUpdateDefaultAddress parameters:dict andApiTyp:CustomerApiTypMain SuccessBlock:^(id responseObject) {
            [strongSelf endReresh];
            if ([responseObject[@"status"] isEqualToString:@"error"]) {
                [strongSelf showErrorTipWithTitle:responseObject[@"error"]];
            }else{
                NSInteger result = [responseObject[@"data"] integerValue];
                if (result) {
                    [strongSelf showSuccessWithType:0 AndTitle:@"设置成功"];
                    [strongSelf loadDataList];
                }else{
                    [strongSelf showErrorTipWithTitle:@"设置失败"];
                }
                
            }
        } Failure:^(NSError *error) {
            [strongSelf endReresh];
            [strongSelf showErrorTipWithTitle:CustomerPoolNetStr];
        }];
    }]];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)selectAddressEditInformation:(NSIndexPath *)indexPath{
    AddNewAddressViewController *newAds = [AddNewAddressViewController new];
    if (indexPath.section < [self.dataList count]) {
        AddressModel *model = self.dataList[indexPath.section];
        newAds.addressModel = model;
        newAds.isEdit = YES;
    }
    TAB_PUSH(self, newAds, YES);
}

- (void)selectAddressDeleteInformation:(NSIndexPath *)indexPath{
    NSLog(@"删除数据%ld",indexPath.section);
    if (indexPath.section >= [self.dataList count]) {
        return;
    }
    AutoWeakSelf
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@"确认要删除该地址?" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [alertController dismissViewControllerAnimated:YES completion:nil];
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        AddressModel *address = self.dataList[indexPath.section];
        NSDictionary *dict = @{@"member_id":K_UserDefault_Read(CustomerUserID)?:@"",@"member_token":K_UserDefault_Read(CustomerUserToken)?:@"",@"address_id":address.address_id};
        __block typeof(weakSelf) strongSelf = weakSelf;
        [[QYNetManager sharedManager]POST:kDeleteAddress parameters:dict andApiTyp:CustomerApiTypMain SuccessBlock:^(id responseObject) {
            [weakSelf endReresh];
            if ([responseObject[@"status"] isEqualToString:@"error"]) {
                [strongSelf showErrorTipWithTitle:responseObject[@"error"]];
            }else{
                NSInteger result = [responseObject[@"data"] integerValue];
                if (result) {
                    [strongSelf showSuccessWithType:0 AndTitle:@"删除成功"];
                    [strongSelf loadDataList];
                }else{
                    [strongSelf showErrorTipWithTitle:@"删除失败"];
                }
            }
        } Failure:^(NSError *error) {
            [weakSelf endReresh];
            [weakSelf showErrorTipWithTitle:CustomerPoolNetStr];
        }];
    }]];
    [self presentViewController:alertController animated:YES completion:nil];
}


#pragma mark - GETTER
- (UIScrollView *)scrollView{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0,0, F_DEVICE_W, F_DEVICE_H - NAVIGATION_BAR_HEIGHT - bottomPadding(100))];
        _scrollView.delegate = self;
        _scrollView.contentSize = CGSizeMake(F_DEVICE_W,F_DEVICE_H - NAVIGATION_BAR_HEIGHT - bottomPadding(100));
    }
    return _scrollView;
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
